package com.mall.server.service.impl;

import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule;
import com.mall.server.model.User;
import com.mall.server.model.dto.LoginRequest;
import com.mall.server.model.dto.TokenResponse;
import com.mall.server.model.dto.VerifyCodeLoginRequest;
import com.mall.server.repository.UserRepository;
import com.mall.server.service.UserService;
import com.mall.server.service.VerificationCodeService;
import com.mall.server.util.JwtUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.ClassPathResource;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;

import javax.annotation.PostConstruct;
import javax.persistence.EntityNotFoundException;
import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.logging.Level;
import java.util.logging.Logger;

@Service
public class UserServiceImpl implements UserService {
    
    private static final Logger logger = Logger.getLogger(UserServiceImpl.class.getName());
    
    // 模拟用户数据存储
    private Map<String, User> userMap = new HashMap<>();
    private List<User> userList = new ArrayList<>();
    
    @Autowired
    private UserRepository userRepository;
    
    @Autowired
    private PasswordEncoder passwordEncoder;
    
    @Autowired
    private JwtUtil jwtUtil;
    
    @Autowired
    private VerificationCodeService verificationCodeService;
    
    private final ObjectMapper objectMapper = new ObjectMapper().registerModule(new JavaTimeModule());
    
    @PostConstruct
    public void init() {
        try {
            // 从JSON文件加载用户数据
            ClassPathResource resource = new ClassPathResource("data/users.json");
            userList = objectMapper.readValue(resource.getInputStream(), new TypeReference<List<User>>() {});
            
            logger.info("从JSON文件加载了 " + userList.size() + " 个用户");
            
            // 将用户添加到映射中，以便按用户名和手机号快速查找
            for (User user : userList) {
                userMap.put(user.getUsername(), user);
                userMap.put(user.getPhone(), user);
            }
            
            logger.info("用户数据初始化完成");
        } catch (IOException e) {
            logger.log(Level.SEVERE, "加载用户数据时出错", e);
            
            // 如果加载失败，使用默认用户
            initDefaultUsers();
        }
    }
    
    private void initDefaultUsers() {
        logger.info("初始化默认用户数据");
        
        User admin = new User();
        admin.setId(1L);
        admin.setUsername("admin");
        admin.setPassword(passwordEncoder.encode("123456"));
        admin.setPhone("13800138000");
        admin.setNickname("管理员");
        admin.setAvatar("https://joeschmoe.io/api/v1/admin");
        admin.setCreatedAt(LocalDateTime.now());
        admin.setUpdatedAt(LocalDateTime.now());
        
        User normalUser = new User();
        normalUser.setId(2L);
        normalUser.setUsername("user");
        normalUser.setPassword(passwordEncoder.encode("123456"));
        normalUser.setPhone("13900139000");
        normalUser.setNickname("普通用户");
        normalUser.setAvatar("https://joeschmoe.io/api/v1/user");
        normalUser.setCreatedAt(LocalDateTime.now());
        normalUser.setUpdatedAt(LocalDateTime.now());
        
        // 将用户添加到列表和映射
        userList.add(admin);
        userList.add(normalUser);
        userMap.put(admin.getUsername(), admin);
        userMap.put(normalUser.getUsername(), normalUser);
        userMap.put(admin.getPhone(), admin);
        userMap.put(normalUser.getPhone(), normalUser);
        
        logger.info("默认用户数据初始化完成");
    }
    
    // 保存用户数据到JSON文件
    private void saveUsersToJson() {
        try {
            String filePath = new ClassPathResource("data").getFile().getAbsolutePath() + "/users.json";
            objectMapper.writerWithDefaultPrettyPrinter().writeValue(new File(filePath), userList);
            logger.info("用户数据已保存到JSON文件");
        } catch (IOException e) {
            logger.log(Level.SEVERE, "保存用户数据时出错", e);
        }
    }
    
    @Override
    public TokenResponse login(LoginRequest loginRequest) {
        logger.info("尝试登录用户: " + loginRequest.getUsername());
        
        // 从映射中查找用户
        User user = userMap.get(loginRequest.getUsername());
        if (user == null) {
            logger.warning("用户不存在: " + loginRequest.getUsername());
            throw new EntityNotFoundException("用户不存在");
        }
        
        // 验证密码
        if (!passwordEncoder.matches(loginRequest.getPassword(), user.getPassword())) {
            logger.warning("密码错误: " + loginRequest.getUsername());
            throw new IllegalArgumentException("密码错误");
        }
        
        // 生成token
        String token = jwtUtil.generateToken(user.getUsername());
        logger.info("登录成功: " + loginRequest.getUsername());
        
        return new TokenResponse(token, user.getUsername(), user.getNickname(), user.getAvatar());
    }
    
    @Override
    public TokenResponse loginWithVerifyCode(VerifyCodeLoginRequest request) {
        logger.info("尝试使用验证码登录: " + request.getPhone());
        
        // 验证码校验
        if (!verificationCodeService.verifyCode(request.getPhone(), request.getCode())) {
            logger.warning("验证码无效或已过期: " + request.getCode());
            throw new IllegalArgumentException("验证码无效或已过期");
        }
        
        // 从映射中查找用户
        User user = userMap.get(request.getPhone());
        if (user == null) {
            // 如果用户不存在，创建一个新用户
            logger.info("用户不存在，创建新用户: " + request.getPhone());
            user = createUserFromPhone(request.getPhone());
        }
        
        // 生成token
        String token = jwtUtil.generateToken(user.getUsername());
        logger.info("验证码登录成功: " + request.getPhone());
        
        return new TokenResponse(token, user.getUsername(), user.getNickname(), user.getAvatar());
    }
    
    @Override
    public User findByUsername(String username) {
        logger.info("查找用户: " + username);
        User user = userMap.get(username);
        if (user == null) {
            throw new EntityNotFoundException("用户不存在");
        }
        return user;
    }
    
    private User createUserFromPhone(String phone) {
        User user = new User();
        user.setId((long) (userList.size() + 1));
        user.setUsername(phone);  // 使用手机号作为用户名
        user.setPhone(phone);
        user.setPassword(passwordEncoder.encode(phone.substring(5)));  // 使用手机号后6位作为初始密码
        user.setNickname("用户" + phone.substring(phone.length() - 4));  // 使用手机号后4位作为昵称
        user.setAvatar("https://joeschmoe.io/api/v1/random");
        user.setCreatedAt(LocalDateTime.now());
        user.setUpdatedAt(LocalDateTime.now());
        
        // 将新用户添加到列表和映射
        userList.add(user);
        userMap.put(phone, user);
        userMap.put(user.getUsername(), user);
        
        // 保存到JSON文件
        saveUsersToJson();
        
        return user;
    }
} 